


#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

IplImage*    g_image    = NULL;
IplImage*    g_gray    = NULL;
int        g_thresh  = 100;
CvMemStorage*  g_storage  = NULL;

static CvMemStorage* storage = 0;


void on_trackbar(int) {
  if( g_storage==NULL ) {
    g_gray = cvCreateImage( cvGetSize(g_image), 8, 1 );
    g_storage = cvCreateMemStorage(0);
  } else {
    cvClearMemStorage( g_storage );
  }
  CvSeq* contours = 0;
  cvCvtColor( g_image, g_gray, CV_BGR2GRAY );
  cvThreshold( g_gray, g_gray, g_thresh, 255, CV_THRESH_BINARY );
  cvFindContours( g_gray, g_storage, &contours );
  cvZero( g_gray );
  if( contours )
    cvDrawContours( 
      g_gray, 
      contours, 
      cvScalarAll(255),
      cvScalarAll(255), 
      100 
    );
  cvShowImage( "Contours", g_gray );
}

int main( int argc, char** argv )
{

	CvCapture* capture = 0;
    	IplImage *frame, *frame_copy = 0;
	
   	CvSize imageSize;
    	
  //if( argc != 2 || !(g_image = cvLoadImage(argv[1])) )
  if( argc != 2)
  return -1;
  

   storage = cvCreateMemStorage(0);
    capture = cvCaptureFromAVI(argv[1]);
    if( !capture )
    {
        fprintf(stderr,"Could not initialize capturing...\n");
        return -1;
    }

    	cvNamedWindow( "Contours", 1 );
	   cvCreateTrackbar( 
	    "Threshold", 
	    "Contours", 
	    &g_thresh, 
	    255, 
	    on_trackbar
	  	);

    if( capture )
    {
        for(;;)
        {
          
	frame = cvQueryFrame(capture);
            if( !frame )
                break;



            if( !g_image )
                g_image = cvCreateImage( cvSize(frame->width,frame->height),
                                            IPL_DEPTH_8U, frame->nChannels );
            if( frame->origin == IPL_ORIGIN_TL )
                cvCopy( frame, g_image, 0 );
            else
                cvFlip( frame, g_image, 0 );

  
  		on_trackbar(0);
  		if( cvWaitKey( 10 ) >= 0 )
                break;
	} 
	cvReleaseImage( &g_image );
        cvReleaseCapture( &capture );
	}
}
